package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室服务端
 */
public class Server {
    private ServerSocket serverSocket;

    //存放对应所有客户端的输出流，用于广播消息
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server() {
        try {
            System.out.println("正在启动服务端");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已连接！");
                //启动一个线程来处理与客户端的交互
                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    /**
     * 该线程任务负责与指定的客户端进行交互
     */
    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;//记录客户端的IP地址

        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过socket获取远端计算机(客户端)的IP地址
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);

                //将该输出流存入到共享的集合中，以便其他ClientHandler可以将消息发给其他的客户端
                synchronized (allOut) {
                    allOut.add(pw);
                }
                //广播该客户端上线的信息
                sendMessage(host + "上线了，当前在线人数:" + allOut.size());

                String line;
                while ((line = br.readLine()) != null) {
                    sendMessage(host + "说:" + line);
                }
            } catch (IOException e) {

            } finally {
                //统一处理该客户端下线后的工作
                //1将该客户端的输出流从allOut中删除
                synchronized (allOut) {
                    allOut.remove(pw);
                }
                sendMessage(host + "下线了，当前在线人数：" + allOut.size());
                //2将socket关闭释放资源
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 将给定的消息发送给所有客户端
         */
        private void sendMessage(String line) {
            synchronized (allOut) {
                System.out.println(host + "说:" + line);
                //将消息发送给所有客户端
                for (PrintWriter p : allOut) {
                    p.println(line);
                }
            }
        }
    }
}
